<template>
  <van-nav-bar :title="t('home.退件接收')" left-arrow @click-left="onClickLeft" />
  <div class="mx-auto mb-20 ">
    <van-cell-group>
      <!-- <van-field v-model="scan" label="" :placeholder="t('returnScan.请扫描大包号')" /> -->
      <van-field v-model="scan" label="" :placeholder="t('returnScan.请扫描退件单号')" @keydown.enter="handleScan" clearable
        id="scan_order" />
      <van-field :style="orderInfo['orderTypeTips'] == '' ? ';display:none' : ''">
        <template #input>
          <span class="w-full p-3 text-5xl text-center text-white" :style="'background:' + orderInfo['status']">{{
            orderInfo["orderTypeTips"] }}</span>
        </template>
      </van-field>

      <van-field>
        <template #input>
          <van-col span="8">
            <van-tag>{{ t("total") }}:{{ dataList.length }}</van-tag>
          </van-col>
          <van-col span="8">
            <van-tag type="success">{{ t("success") }}:{{ dataList.filter((i) => i.status).length }}</van-tag>
          </van-col>
          <van-col span="8">
            <van-tag type="danger">{{ t("fail") }}:{{ dataList.filter((i) => !i.status).length }}</van-tag>
          </van-col>
        </template>
      </van-field>

      <van-field>
        <template #input>
          <van-col span="12"> {{ t("returnScan.退件单号") }} </van-col>
          <van-col span="12">
            {{ t("returnScan.操作记录") }}
            <!-- <van-tag  
              >{{ dataList.length }}</van-tag>
              <van-tag  type="success"
              >{{ dataList.filter(i=>i.status).length }}</van-tag>
              <van-tag  type="danger"
              >{{ dataList.filter(i=>!i.status).length }}</van-tag> -->
          </van-col>
        </template>
      </van-field>

      <template v-if="dataList.length > 0">
        <template v-for="item in dataList" :key="item.id">
          <van-field>
            <template #input>
              <van-col span="12" :style="item.status==1
                ? 'color:green;'
                : item.status==2
                ? 'color:#ffca00;'
                : 'color:red;'
                ">
                <span class="p-1 text-sm text-white bg-green-400 rounded">{{
                  item.orderTypeTips
                }}</span>
                <div></div>
                {{ item.packageNo }}
              </van-col>
              <van-col span="12" :style="item.status==1
                ? 'color:green;'
                : item.status==2
                ? 'color:#ffca00;'
                : 'color:red;'
                ">
                {{ item.info }}
              </van-col>
            </template>
          </van-field>

        </template>
      </template>
      <van-empty v-else :description="t('noData')" :image="img_index_path" />
    </van-cell-group>

    <van-popup v-model:show="headlessFormState.show" round lock-scroll safe-area-inset-top safe-area-inset-bottom
      position="bottom" :style="{ height: '80%' }">
      <div class="p-2 mx-auto">
        <van-field>
          <template #input>
            <span class="w-full p-3 text-xl text-center text-gray">{{
              t("returnScan.unknown")
            }}</span>
          </template>
        </van-field>
        <van-cell-group>
          <!-- <van-field v-model="scan" label="" :placeholder="t('returnScan.请扫描大包号')" /> -->
          <van-field v-model="scan" :label="t('returnScan.认领单号')" />
          <van-field id="head_less_form_storage_block" required v-model="headlessFormState.storageBlock"
            :label="t('returnScan.暂存库位')" :placeholder="t('returnScan.请输入暂存库位')" />
          <van-field v-model="headlessFormState.time" readonly :label="t('returnScan.到货时间')"
            :placeholder="t('returnScan.请输入到货时间')" />
          <van-field v-model="headlessFormState.desc" :label="t('returnScan.退件描述')"
            :placeholder="t('returnScan.请输入退件描述')" />
          <van-field :label="t('returnScan.图片')">
            <template #input>
              <van-uploader v-model="headlessFormState.fileList" :after-read="afterRead" />
            </template>
          </van-field>
          <van-field>
            <template #input>
              <van-button size="small" class="w-full p-8" type="success" @click="handleHeadlessFormSubmit">{{
                t("returnScan.确认") }}</van-button>
            </template>
          </van-field>
        </van-cell-group>
      </div>
    </van-popup>
    <div class="absolute inset-x-0 bottom-0">
      <van-field>
        <template #input>
          <van-button type="success" size="small" @click="() => {
            clearData();
            dataList = [];
          }
            " class="w-full p-8">{{ t("returnScan.清除") }}</van-button>
        </template>
      </van-field>
    </div>
  </div>
</template>

<script setup lang="ts">
import img_index_path from "~/noData.png";
import { postRequest } from "@/api";
import { useI18n } from "vue-i18n";
import { AppToast } from "@/utils/appToast";
import { DEPOT_CODE } from "@/utils/constant";
const { t } = useI18n();

onMounted(() => {
  const scan_order = document.getElementById("scan_order");
  scan_order.focus();
});

const onClickLeft = () => history.back();
const scan = ref("");
const OPERTYPE = ref("");

const afterRead = (file) => {
  const formData = new FormData();
  formData.append("file", file.file);

  file.status = "uploading";
  file.message = t('uploading');
  postRequest("/ReturnOrderService/claim/uploadImage", formData).then((response) => {
    if (response.status === 200) {
      file.url = response.data;
      file.status = "done";
      file.message = t("returnScan.上传成功");
    } else {
      file.status = "failed";
      file.message = t("returnScan.上传失败");
      AppToast(response.message, "fail");
    }
  }).catch(() => {
    file.status = "failed";
    file.message = t("returnScan.上传失败");
  });


  // const reader = new FileReader();
  // reader.readAsDataURL(file.file);
  // reader.onload = (e) => {
  //   file.status = "uploading";
  //   file.message = t('uploading') ;
  //   postRequest("/ReturnOrderService/claim/uploadImage", {
  //     // bucket: UPLOAD_BUCKET,
  //     // originalFileName: scan.value,
  //     // dataBase64: base64Str,
  //     // // "2022-11-14T08:43:19.006Z"
  //     // createDate: new Date().toISOString(),
  //     // createUser: JSON.parse(localStorage.getItem(STORAGE_USER_DATA_KEY))["account"],
  //     // expire: UPLOAD_EXPIRE_TIME,
  //     file: file.file,
  //   }).then((res) => {
  //     if (res.code == 200) {
  //       file.url = res.data;
  //       file.status = "done";
  //       file.message = t("returnScan.上传成功");
  //       imagesList.value.push(file.url);
  //     } else {
  //       file.status = "failed";
  //       file.message = t("returnScan.上传失败");
  //     }
  //   });
  // };
};
const headlessFormState = reactive({
  show: false,
  storageBlock: "",
  time: "",
  desc: "",
  fileList: [],
});
const orderInfo = reactive({
  status: null,
  orderTypeTips: "",
});
const dataList = ref([]);
// localStorage.setItem('userInfo',JSON.stringify({"account":"王俊","password":"123456","organizationName":"技术产品中心","token":"5c34bd829f7c4495b23d70b29247e3c1"}))
// localStorage.setItem('token','123')
function getPathParamsByName(name) {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}
const init = async () => {
  OPERTYPE.value = getPathParamsByName("operType");
};
init();

const handleHeadlessFormSubmit = () => {
  if (headlessFormState.storageBlock) {
    //提交
    postRequest("/ReturnOrderService/claim/add", {
      packageNumber: scan.value,
      storageBlock: headlessFormState.storageBlock,
      depot: DEPOT_CODE,
      // time: headlessFormState.time,
      memo: headlessFormState.desc,
      // reason: headlessFormState.desc,
      // fileList: headlessFormState.fileList
      images: headlessFormState.fileList.filter((item) => item.url).map((item) => item.url),
    }).then((res) => {
      if (res.status === 200) {
        //关闭弹窗
        headlessFormState.show = false;
        orderInfo["status"] = "green";
        dataList.value.unshift({
          id: dataList.value.length + 1,
          packageNo: scan.value,
          status: 1,
          // orderType: res.data.type,
          orderTypeTips: orderInfo["orderTypeTips"],
          info: t("success"),
        });
        scan.value = "";
        AppToast(t("success"));

        const scan_order = document.getElementById("scan_order");
        scan_order.focus();
      } else {
        AppToast(t("fail") + " " + res.message, "fail", true);
      }
    });
    //修改页面数据
  } else {
    AppToast(t("returnScan.请输入暂存库位"), "danger", true);
    return;
  }
};
const clearData = () => {
  //clean orderInfo
  orderInfo["status"] = null;
  orderInfo["orderTypeTips"] = "";

  headlessFormState["show"] = null;
  headlessFormState["storageBlock"] = "";
  headlessFormState["time"] = new Date().toLocaleString();
  headlessFormState["desc"] = "";
  headlessFormState["fileList"] = [];
};
const handleScan = () => {
  clearData();
  // [
  //     {
  //       url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg',
  //       status: 'uploading',
  //       message: '上传中...',
  //     },
  //     {
  //       url: 'https://fastly.jsdelivr.net/npm/@vant/assets/tree.jpeg',
  //       status: 'failed',
  //       message: '上传失败',
  //     },
  //   ]

  // scan.value   如果是 -K 或者 -R结尾 ，则去掉
  if (scan.value.endsWith("-K") || scan.value.endsWith("-R")) {
    scan.value = scan.value.substring(0, scan.value.length - 2);
  }
  if (scan.value) {
    // postRequest("/mock", {
    //   packageNumber: scan.value,
    //   depotCode: DEPOT_CODE,
    //   orderType: Math.random() > 0.33 ? ( Math.random() > 0.5?'tms':'wlms') : 'unknown',
    postRequest("/ReturnOrderService/checkin", {
      packageNumber: scan.value,
      depotCode: DEPOT_CODE,
    }).then((res) => {


      // test code
      // console.log("ress", res);
      // res.data.isTestQuality = true;
      // orderInfo["status"] = "yellow";
      // dataList.value.unshift({
      //   id: dataList.value.length + 1,
      //   packageNo: scan.value,
      //   status: 2,
      //   orderType: res.data.type,
      //   orderTypeTips: orderInfo["orderTypeTips"],
      //   info: t("returnScan.请去质检" ),
      // });
      // scan.value = "";
      // AppToast(t("returnScan.请去质检" ));
      // return


      if (res.status === 200) {
        orderInfo["orderTypeTips"] = t("returnScan." + res.data.orderType);
        //如果是无头件
        if (res.data.orderType == "unknown") {
          // 弹窗
          headlessFormState.show = true;
          setTimeout(() => {
            const head_less_form_storage_block = document.getElementById(
              "head_less_form_storage_block"
            );
            head_less_form_storage_block.focus();
          }, 500);

          return;
        }

        if (res.data.isTestQuality) {
          orderInfo["status"] = "yellow";
          dataList.value.unshift({
            id: dataList.value.length + 1,
            packageNo: scan.value,
            status: 2,
            orderType: res.data.type,
            orderTypeTips: orderInfo["orderTypeTips"],
            info: t("success")+", "+t("returnScan.请去质检" ),
          });
          scan.value = "";
          AppToast(t("success")+", "+t("returnScan.请去质检" ));
        } else {
          orderInfo["status"] = "green";
          dataList.value.unshift({
            id: dataList.value.length + 1,
            packageNo: scan.value,
            status: 1,
            orderType: res.data.type,
            orderTypeTips: orderInfo["orderTypeTips"],
            info: t("success"),
          });
          scan.value = "";
          AppToast(t("success"));
        }


      } else {
        orderInfo["status"] = "red";
        dataList.value.unshift({
          id: dataList.value.length + 1,
          packageNo: scan.value,
          status: 0,
          // orderType: res.data.type,
          // orderTypeTips: orderInfo['orderTypeTips'],
          orderTypeTips: t("returnScan.操作失败"),
          info: t("fail") + " " + res.message,
        });
        scan.value = "";
        AppToast(t("fail") + " " + res.message, "fail", true);
      }
    });
  } else {
    AppToast(t("returnScan.请扫描退件单号"), "danger", true);
  }
};
</script>

<style lang="less" scoped></style>
